from flask_wtf import FlaskForm
from marshmallow import Schema, fields, pre_dump

from internal.entitry.tickets_entitry import ProxyType
from internal.schema.schema import ListField, DictField

from wtforms.fields.simple import TelField,StringField
from wtforms.validators import DataRequired, Length, Optional, ValidationError

from pkg.paginator import PaginatorReq


class CreateTicketsForm(FlaskForm):
    agencyCheckGuides =DictField("agencyCheckGuides")
    data = ListField("data")
    def validate_data(self,field:ListField):
        if not isinstance(field.data,list):
            raise ValidationError("必须为列表")
        if len(field.data) == 0:
            raise ValidationError("导游信息不能为空")
        for item in field.data:
            if not item.get("agencyCheckGuides"):
                raise ValidationError("agencyCheckGuides不能为空")
            if not item.get("agencyCheckGuides").get("guideName"):
                raise ValidationError("导游姓名不能为空")
            if not item.get("agencyCheckGuides").get("cardType"):
                raise ValidationError("导游证件类型不能为空")
            if not item.get("agencyCheckGuides").get("guideIdentify"):
                raise ValidationError("导游证件号不能为空")
            if not item.get("agencyCheckGuides").get("guideNo"):
                raise ValidationError("导游证不能为空")
            if not item.get("agencyCheckGuides").get("guideMobile"):
                raise ValidationError("导游手机号不能为空")

class AgencyCheckGuideSchema(FlaskForm):
    data = ListField("data")
    def validate_data(self,field:ListField):
        index=0
        print(field.data)
        if not isinstance(field.data,list):
            raise ValidationError("必须为列表")
        if len(field.data) == 0:
            raise  ValidationError("团队信息不能为空")
        for item in field.data:

            if not item.get("bash_id"):
                raise  ValidationError("批次id不能为空")
            if not item.get("travelAgencyName"):
                raise ValidationError("旅行社名称不能为空")
            if not isinstance(item.get("user"),dict):
                raise ValidationError("user信息必须为对象")
            if not item.get("user").get("playDate"):
                raise ValidationError("预约日期不能为空")
            if not isinstance(item.get("user").get("playDate"),list):
                raise ValidationError("预约日期必须是列表")
            if len(item.get("user").get("playDate"))==0:
                raise ValidationError("预约日期不能为空")
            if not item.get("user").get("addTourists"):
                raise ValidationError("addTourists不能为空")
            if not isinstance(item.get("user").get("addTourists"),list):
                raise ValidationError("addTourists必须为列表")
            tourists_without_name = []
            for index, data in enumerate(item.get("user", {}).get("addTourists", [])):
                if not data.get("touristName"):
                    tourists_without_name.append(index)

            # 如果不存在 touristName 的数据数量大于1，删除这些对象
            if len(tourists_without_name) > 1:
                # 从后往前删除，避免索引变化问题
                for index in sorted(tourists_without_name, reverse=True):
                    item["user"]["addTourists"].pop(index)
            else:
                # 如果只有1个或没有缺失 touristName 的数据，执行原有的验证逻辑
                for index, data in enumerate(item.get("user", {}).get("addTourists", [])):
                    if not data.get("touristName"):
                        raise ValidationError("成员姓名不能为空")
                    if not data.get("cardType"):
                        raise ValidationError("证件类型不能为空")
                    if not data.get("cardNumber"):
                        raise ValidationError("证件号不能为空")
                    if not data.get("origin"):
                        raise ValidationError("省/市不能为空")

class DelTourGuideWithOther(FlaskForm):
    bash_ids = ListField("bash_ids")

    def validate_bash_ids(self,field:ListField):
        if not isinstance(field.data,list):
            raise ValidationError("类型错误必须为列表")
        if len(field.data) == 0:
            raise ValidationError("批次id不能为空")
class DelAgency(FlaskForm):
    agency_ids = ListField("agency_ids")
    def validate_bash_ids(self, field: ListField):
        if not isinstance(field.data, list):
            raise ValidationError("类型错误必须为列表")
        if len(field.data) == 0:
            raise ValidationError("组id不能为空")

class DelUser(FlaskForm):
    user_ids = ListField("user_ids")
    def validate_user_ids(self, field: ListField):
        if not isinstance(field.data, list):
            raise ValidationError("类型错误必须为列表")
        if len(field.data) == 0:
            raise ValidationError("成员id不能为空")

class TourGuideWithListSchema(PaginatorReq):
    travel_agency_phone =  StringField('travel_agency_phone', validators=[Optional()]) #导游手机号
    name = StringField('name', validators=[Optional()]) #导游姓名
    bash_id = StringField('bash_id', validators=[Optional()])
    enabled = StringField('enabled', validators=[Optional()])
class UpdateEnabledSchema(FlaskForm):
    enabled = StringField('enabled', validators=[Optional()])
    guide_ids = ListField("guide_ids")
    def validate_guide_ids(self,field: ListField):
        if not isinstance(field.data, list):
            raise ValidationError("导游id必须为列表")
        if len(field.data) == 0:
            raise ValidationError("导游id不能为空")


class UpdatePlayDateSchema(FlaskForm):
    agency_id = StringField('agency_id', validators=[DataRequired("旅行社id不能为空")])
    date_str = StringField('date_str', validators=[DataRequired("预约日期不能为空")])
class ReSubTickets(FlaskForm):
    type = StringField('type', validators=[DataRequired("代理类型不能为空")],default=ProxyType.CUSTOM.value)
    secret_id = StringField('secret_id', validators=[Optional()])

class SubTickets(FlaskForm):
    ids = ListField("ids")
    grounp_ids = ListField("grounp_ids")
    type = StringField('type', validators=[DataRequired("代理类型不能为空")],default=ProxyType.CUSTOM.value)
    secret_id = StringField('secret_id', validators=[Optional()])
    secret_key = StringField('secret_key', validators=[Optional()])
    def validate_grounp_ids(self,field: ListField):
        if not isinstance(field.data, list):
            raise ValidationError("组id必须为列表")
        if len(field.data) == 0:
            raise ValidationError("组不能为空")

    def validate_ids(self,field:ListField):
        if not isinstance(field.data,list):
            raise ValidationError("ids必须为列表")
        if len(field.data) == 0:
            raise ValidationError("ids不能为空")

    # def validate_user(self,field:ListField):
    #     if not isinstance(field.data,dict):
    #         raise ValidationError("成员信息类型错误，必须为字典")
    #
    #
    #     if not isinstance(field.data.get("addTourists"), list):
    #         raise ValidationError("类型错误，addTourists必须是列表")
    #     for d in field.data.get("addTourists"):
    #         if not isinstance(d, dict):
    #             raise ValidationError("类型错误，addTourists列表内必须为字典")

    def validate_agencyCheckGuides(self, field: ListField) -> None:
        if not isinstance(field.data, list):
            raise ValidationError("导游必须是列表")
        if len(field.data) == 0:
            raise ValidationError("导游信息不能为空")
        for item in field.data:
            if not item.get("guideName"):
                raise ValidationError("导游姓名不能为空")
            if not item.get("guideIdentify"):
                raise ValidationError("身份证号不能为空")
            if not item.get("cardType"):
                raise ValidationError("导游证件类型不能为空")
            if not item.get("guideNo"):
                raise ValidationError("导游证件号不能为空")
            if not item.get("guideMobile"):
                raise ValidationError("导游手机号号不能为空")
class TicketsWithListPageSchema(PaginatorReq):
    bash_id = StringField('bash_id', validators=[Optional()])
    guide_name =  StringField('guide_name', validators=[Optional()])
    travel_agencies_name = StringField('travel_agencies_name', validators=[Optional()])
    status = StringField('status', validators=[Optional()])
    created_date = StringField('created_date', validators=[Optional()])